<?php

use think\facade\Filesystem;

class Wechat
{

    static function getAccessToken()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token';

        $client = new \GuzzleHttp\Client();

        $response = $client->get($url, [
            'query' => [
                'grant_type' => 'client_credential',
                'appid' => env('TENCENT.APP_ID'),
                'secret' => env('TENCENT.APP_SECRET')
            ]
        ])->getBody()->getContents();

        $response = json_decode($response, true);

        if (isset($response['errcode'])) {
            throw new Exception($response['errmsg']);
        }

        return $response['access_token'];
    }

    static function getQRCode($query, $path = 'pages/contract-partner/index')
    {
        $accessToken = self::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={$accessToken}";

        $client = new \GuzzleHttp\Client();

        $response = $client->post($url, [
            'json' => [
                'path' => $path . ($query ? "?" . $query : '')
            ]
        ])->getBody()->getContents();

        $filename = 'qrcode/' . md5(uniqid()) . '.png';

        Filesystem::disk('public')->write($filename, $response);

        self::uploadFile('uploads/' . $filename);
        return 'uploads/' . $filename;
    }

    static function generateUrlLink($query, $path = 'pages/contract-partner/index')
    {
        $accessToken = self::getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" . $accessToken;
        $client = new \GuzzleHttp\Client();

        $response = $client->post($url, [
            'json' => [
                'path' => $path,
                'query' => $query
            ]
        ])->getBody()->getContents();
        $response = json_decode($response, true);
        if ($response['errcode'] == 0){
            return $response['url_link'];
        }
        throw new \think\exception\HttpException(500,$response['errmsg']);
    }


    static function uploadFile($path)
    {
        $uploadUrls = self::getUploadUrl($path);
        try {
            $curlFile = new CURLFile(__ROOT__ . '/' . $path);
            $curlFile->setMimeType(mime_content_type(__ROOT__ . '/' . $path));
            $curlFile->setPostFilename(basename(__ROOT__ . '/' . $path));

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $uploadUrls['url']);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, [
                'key' => $path,
                'Signature' => $uploadUrls['authorization'],
                'x-cos-security-token' => $uploadUrls['token'],
                'x-cos-meta-fileid' => $uploadUrls['cos_file_id'],
                'file' => $curlFile
            ]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            curl_close($ch);
            if ($httpCode === 204) {
                return true;
            }
        } catch (Throwable $throwable) {
        }
        return false;
    }

    static function getUploadUrl($path)
    {
        $accessToken = self::getAccessToken();
        $url = "https://api.weixin.qq.com/tcb/uploadfile?access_token=" . $accessToken;
        $client = new \GuzzleHttp\Client();
        $response = $client->post($url, [
            'json' => [
                'env' => env('TENCENT.CLOUD_ENV'),
                'path' => $path
            ]
        ])->getBody()->getContents();

        $response = json_decode($response, true);

        if (isset($response['errcode']) && $response['errcode'] != 0) {
            throw new Exception($response['errmsg']);
        }

        return $response;
    }
}